import Config from './config';

function setError(err) {
  // switch (err && err.error) {
  //   case 11:
  //     console.error('httpRequest 无权跨域, 错误编码: ' + err.error);
  //     break;
  //   case 12:
  //     console.error('httpRequest 网络出错, 错误编码: ' + err.error);
  //     break;
  //   case 13:
  //     console.error('httpRequest 超时, 错误编码: ' + err.error);
  //     break;
  //   case 14:
  //     console.error('httpRequest 解码失败, 错误编码: ' + err.error);
  //     break;
  //   case 19:
  //     console.error('httpRequest HTTP错误, 错误编码: ' + err.error);
  //     break;
  //   default:
  //     console.error('httpRequest 请求错误, 错误编码: ' + err.error);
  // }
  // my.alert({ content: '网络错误，请稍后再试:' + err.error });
  console.error('request fail：', err);
  my.hideLoading();
  my.showToast({
    type: 'none',
    content: '网络错误，请稍后再试:' + (err && err.error),
    duration: 2000,
  });
}

const Http = {
  _hoststr: Config._hoststr,
  _timeout: 30000,
  _source: 'native',
  _token: '',
  _appId: Config.appid,
  _channelNo: Config.channelNo,
  _requestPath: Config.requestPath,
  _storeCode: '',
  reConstruct: function (url, headers, noPath) {
    if (noPath) {
      url = this._hoststr + url;
    } else {
      url = this._hoststr + this._requestPath + url;
    }

    // 增加 headers['Token']
    if (typeof headers !== 'object') {
      console.error('Http: headers is not object!!');
    } else {
      headers['Content-Type'] = 'application/json;charset=UTF-8';
      headers['ChannelNo'] = this._channelNo; // 在headers 中传渠道号 -- 支付宝小程序
      headers['launchSource'] = this._source; // 在headers 中传小程序启动来源
      headers['Token'] = this._token;
      headers['appId'] = this._appId;
      headers['storeCode'] = this._storeCode;
    }
    return [url, headers];
  },
  get: (url, params = {}, headers = {}, usrTimeout = null, errorCallback, completeCallback) => {
    [url, headers] = Http.reConstruct(url, headers, params && params.noPath);
    params._t = new Date().getTime();
    return new Promise((resolve, reject) => {
      my.request({
        url: url,
        method: 'GET',
        data: params,
        timeout: usrTimeout || Http._timeout,
        headers: headers,
        dataType: 'json',
        success: function (res) {
          if (res) {
            // if (res.data.code == '1001') {
            // 用户未登陆的错误编码
            // my.confirm({
            //    content: '未登陆。点击 “确认” 按钮将重新授权登陆',
            //    confirmButtonText: '确认',
            //    cancelButtonText: '取消',
            //    success: (result) => {
            //      if (result.confirm) { // true or false

            //      }
            //    },
            //  });
            //   resolve(res.data);
            // } else {
            resolve(res.data);
            // }
          } else {
            reject(res);
            setError(res);
          }
        },
        fail: function (err) {
          reject(err);
          setError(err);
          if (typeof errorCallback === 'function') {
            errorCallback(err);
          }
        },
        complete: function (res) {
          if (typeof completeCallback === 'function') {
            completeCallback(res);
          }
        },
      });
    });
  },
  post: (url, params = {}, headers = {}, usrTimeout = null, errorCallback, completeCallback) => {
    [url, headers] = Http.reConstruct(url, headers, params && params.noPath);
    return new Promise((resolve, reject) => {
      my.request({
        url: url,
        method: 'POST',
        data: JSON.stringify(params),
        timeout: usrTimeout || Http._timeout,
        headers: headers,
        dataType: 'json',
        success: function (res) {
          if (res) {
            resolve(res.data);
          } else {
            reject(res);
            setError(res);
          }
        },
        fail: function (err) {
          reject(err);
          setError(err);
          if (typeof errorCallback === 'function') {
            errorCallback(err);
          }
        },
        complete: function (res) {
          if (typeof completeCallback === 'function') {
            completeCallback(res);
          }
        },
      });
    });
  },
  request: (url, params = {}, method = 'GET', headers = {}, usrTimeout = null, errorCallback, completeCallback) => {
    [url, headers] = Http.reConstruct(url, headers, params && params.noPath);
    params._t = new Date().getTime();
    let requestParams = params;
    if (method == 'POST') {
      requestParams = JSON.stringify(params);
    }
    return new Promise((resolve, reject) => {
      my.request({
        url: url,
        method: method,
        data: requestParams,
        timeout: usrTimeout || Http._timeout,
        headers: headers,
        dataType: 'json',
        success: function (res) {
          if (res) {
            resolve(res.data);
          } else {
            reject(res);
            setError(res);
          }
        },
        fail: function (err) {
          reject(err);
          setError(err);
          if (typeof errorCallback === 'function') {
            errorCallback(err);
          }
        },
        complete: function (res) {
          if (typeof completeCallback === 'function') {
            completeCallback(res);
          }
        },
      });
    });
  },
};

export default Http;
